define(['jquery', 'api', 'util', 'user', 'Vue', 'swiper', 'text!pages/index/index.html', 'pages/index/goodsModel'], function($, api, util, user, Vue, Swiper, tpl, goodsModel) {
    var vm,
            swiper,
            swiperTab,
            ver = '?ver=' + new Date().format('yyyyMMddh'),
            hqTimer,
            groupTimer,
            goodsTimer,
            flashsaleTimer = {}, //抢购数据请求定时器
            flashsalenextTimer = {}, //下一场抢购数据请求定时器
            endtimelimitChange = {}, //保存不断减少的抢购结束时间
            STATUS = {'49': '展示期', '50': '认购期', '53': '流通期', '54': '交易结束', '55': '认购结束'},
    STATUS_PRICE = {'49': '预定价格', '50': '认购价格', '53': '当前价格'},
    controller = {
        init: function() {
            //在这里清除定时，是为了避免被挤下线后重新进入页面出现倒计时加倍
            this.clearFullTimer();

            api.setTitle(L('html_title'));
            api.footerShow(1);//显示底部导航
            api.initFooter(0);//底部导航图标高亮顺序
            api.headerShow(0);

            if (vm) {
                vm.show = true;
            } else {
                this.render();
            }

            this.initSwiper();
            this.loadGroups();
            this.loadGoodsInfo();

        },
        render: function() {
            var that = this;
            $('#index').append('<div id="indexCt"></div>');

            vm = new Vue({
                el: '#indexCt',
                data: {
                    show: true,
                    advSrc: [
                        '/static/img/1.jpg' + ver,
                        '/static/img/2.jpg' + ver,
                        '/static/img/3.jpg' + ver,
                        '/static/img/4.jpg' + ver
                    ],
                    groups: [],
                    idToGroup: {},
                    goods_arr: [], //当前商品列表数据
                    code2goods: {}, // {goodscode：goods}
                    code2hq: {}, //{goodscode:行情对象}
                    codeToFlashsale: {}, //{goodscode:抢购}
                    codeToFlashsaleNext: {}, //{goodscode:抢购}
                    tabIndex: '0'	//tab索引code，'0'所有
                },
                filters: {
                    priceFormat: function(v, mindecimal) {
                        return v ? util.priceFormat(mindecimal, v) : '';
                    },
                    status: function(s) {
                        return STATUS[s] ? STATUS[s] : '';
//     	         		return s == 50 ? L('认购期') : L('交易期');
                    },
                    statusPrice: function(s, goodscode) {
                        if (s == 50 && typeof vm.code2goods[goodscode] != 'undefined' && typeof vm.code2goods[goodscode].flashsale != 'undefined' && vm.code2goods[goodscode].flashsale.status === '1') {
                            return '抢购价格';
                        }
                        return STATUS_PRICE[s] ? STATUS_PRICE[s] : '当前价格';
                    }
                },
                methods: {
                    tabChange: function(gid) { //切换商品类型
                        this.tabIndex = gid;

                        //替换商品数据 goods_arr
                        var temp = [];
                        if (gid !== '0' && this.idToGroup[gid]) {
                            //商品原有顺序插入符合该分类的数组
                            for (goodscode in goodsModel.codeToGoods) {
                                if ($.inArray(goodscode, this.idToGroup[gid].relationgoods) >= 0) {
                                    temp.push(goodsModel.codeToGoods[goodscode]);
                                }
                            }
                        } else {
                            temp = goodsModel.goodsOriginal;
                        }
                        this.goods_arr = temp;
                    },
                    buy: function(id, c, goods) {
                        api.setGoods(goods);

                        if (c == 49) {//展示期
                            location.hash = ['#/index/productshow/', id].join('');
                            return;
                        }
                        location.hash = ['#/index/product', c == 50 || c == 55 ? 'detail' : 'trade', '/', id].join('');
                    }
                },
                template: tpl
            })

        },
        timer: function() {
            var that = this,
                    cb = function() {
                        if (hqTimer)
                            clearTimeout(hqTimer);
                        that.timer();
                    };
            api.quotations(
                    {goodscode: Object.keys(vm.code2goods).join(',')},
            function(rs) {
                if (rs.retcode === '0' && rs.data) {
                    that.refreshHq.call(that, rs.data);
                    if (vm.show) {
                        hqTimer = setTimeout(cb, util.cfg.refreshTime);
                    }
                }
            },
                    function(xhr, status) {
                        hqTimer = setTimeout(cb, util.cfg.refreshTime);
                    }
            )
        },
        refreshHq: function(goodsHqAll) {
            for (i in goodsHqAll) {
                var code = goodsHqAll[i].slsymbol.goodscode,
                        issuestatus = vm.code2goods[code].issuestatus, // 商品状态
                        mindecimal = !isNaN(vm.code2goods[code].mindecimal) ? vm.code2goods[code].mindecimal : 0,
                        price = !isNaN(goodsHqAll[i].price) ? goodsHqAll[i].price : 0, // 当前价没有就取昨收价
                        yesclose = !isNaN(goodsHqAll[i].yesclose) ? goodsHqAll[i].yesclose : 0, // 昨收价
                        price = price == 0 ? yesclose : price;

                if (issuestatus == '53') {
                    // 流通期
                    price = price == 0 ? '0.00' : util.priceFormat(mindecimal, price);
                } else {
                    // 展示期、认购期取发行价格
                    price = util.priceFormat(mindecimal, vm.code2goods[code].issueprice);
                }

                // 行情渲染
                $("#hq" + code).html(price);
            }
        },
        initSwiper: function() {
            if (!swiper) {
                swiper = new Swiper('#swiper-container', {
                    autoplay: 5000, //可选选项，自动滑动
                    pagination: '.swiper-pagination',
                    paginationClickable: true,
                    autoplayDisableOnInteraction: false
                });
            }
            if (!swiperTab) {
                swiperTab = new Swiper('#J_TabSwiperContainer', {
                    slidesPerView: 4,
//			        slidesPerView: 'auto',
                    spaceBetween: 30,
                    freeMode: true,
//			        autoplayDisableOnInteraction : false
                    observer: true, //修改swiper自己或子元素时，自动初始化swiper
                    observeParents: true//修改swiper的父元素时，自动初始化swiper
                });
            }
        },
        loadGroups: function() { //商品组
            if (groupTimer)
                clearTimeout(groupTimer);
            var that = this,
        		items = [];
            api.groupInfo(
                    function(rs) {//成功
                        if (rs.retcode === '0') {
                            
                            if (rs.data && rs.data.length) {
                                items = rs.data;
                                items.unshift({labelid: '0', labelname: '全部'}); //预留2个重叠
                                vm.groups = items;
                                items.map(function(item) {
                                    vm.idToGroup[item.labelid] = item;
                                });
//                              that.loadGoodsInfo(); //载入商品
                            } else {
                            	items.unshift({labelid: '0', labelname: '全部'}); //预留2个重叠
                            	vm.groups = items;
                            }
                        } else {
                            groupTimer = setTimeout(that.loadGroups(), 2000);
                        }
                    },
                    function(xhr, status) {//失败
                        groupTimer = setTimeout(that.loadGroups(), 2000);
                    }
            );
        },
        loadGoodsInfo: function() {
            if (goodsTimer)
                clearTimeout(goodsTimer);
            var that = this,
                    cb = function() {
                        // 清除定时器
                        that.clearFullTimer();
                        // 商品行情
                        that.timer();
                        // 有进行中的抢购、或者下一场的
                        if (Object.keys(vm.codeToFlashsale).length || Object.keys(vm.codeToFlashsaleNext).length) {
                            //抢购倒计时
                            setTimeout(that.buyTimer(), 1000);
                        }
                        // 有下一场的抢购
                        if (Object.keys(vm.codeToFlashsaleNext).length) {
                            for (code in vm.codeToFlashsaleNext) {
                                var startdate = new Date(vm.codeToFlashsaleNext[code].starttime * 1000).format('yyyy-MM-dd hh:mm:ss');
                                vm.code2goods[code].nextFlashsaleStarttime = '下一场抢购时间 ' + startdate;
                            }
                        }
                    };

            api.goodsInfo({
                data: {sort: 50},
                success: function(rs) {
                    if (rs.retcode === '0') {
                        if (rs.data && rs.data.length) {
                            goodsModel.addGoods(rs.data);//存入商品模型
                            vm.goods_arr = rs.data;
                            vm.code2goods = goodsModel.codeToGoods;

                            vm.goods_arr.map(function(goods) {

                                // 认购期
                                if (goods.issuestatus == goodsModel.status_rgq) {
                                    if (typeof goods.flashsale != 'undefined') {
                                        // 进行中的场抢购数据
                                        if (goods.flashsale.status === '1') {
                                            vm.codeToFlashsale[goods.goodscode] = goods.flashsale;
                                        }
                                        // 没开始，就算下一场
                                        else if (goods.flashsale.status === '0') {
                                            vm.codeToFlashsaleNext[goods.goodscode] = goods.flashsale;
                                        }
                                    }
                                    if (typeof goods.flashsalenext != 'undefined') {
                                        // 下一场场抢购数据
                                        vm.codeToFlashsaleNext[goods.goodscode] = goods.flashsalenext;
                                    }
                                }
                            });

                            cb();
                        } else {
                            goodsTimer = setTimeout(that.loadGoodsInfo(), 2000);
                        }
                    }
                },
                error: function() {
                    goodsTimer = setTimeout(that.loadGoodsInfo(), 2000);
                }
            })
        },
        buyTimer: function() {//抢购计时
            var that = this;

            for (code in vm.codeToFlashsale) {
                var goods = vm.code2goods[code];
                vm.code2goods[code].issueprice = vm.codeToFlashsale[code].iprice;
            }

            // 计时开始！
            var nowtimelimit;
            flashsaleTimer = setInterval(function() {
                var t = '',
                        timego = function(code) {
                            var zero = function(n) {
                                var n = parseInt(n, 10);
                                if (n > 0) {
                                    if (n <= 9) {
                                        n = "0" + n;
                                    }
                                    return String(n);
                                } else {
                                    return "00";
                                }
                            }

                            nowtimelimit = new Date().getTime();
                            var endtimelimit = endtimelimitChange[code],
                                    t = endtimelimit - nowtimelimit,
                                    d = 0,
                                    h = 0,
                                    m = 0,
                                    s = 0;

                            if (t >= 0) {
                                d = Math.floor(t / 1000 / 60 / 60 / 24);
                                h = Math.floor(t / 1000 / 60 / 60 % 24);
                                m = Math.floor(t / 1000 / 60 % 60);
                                s = Math.floor(t / 1000 % 60);
                            }

//console.log(code,(d),(h),(m),(s));

                            if (d <= 0 && h <= 0 && m <= 0 && s <= 0) {
                                // 抢购结束,删除倒计时,删除内存数据
                                delete vm.codeToFlashsale[code];
                                $("#time" + code).html('').addClass('none');

                                if (flashsaleTimer)
                                    clearTimeout(flashsaleTimer);//进行场次
                                //that.loadGoodsInfo();
                                return;
                            } else {
                                t = [zero(h), zero(m), zero(s)].join(':');
                                t = '正在抢购中，距结束仅剩 ' + t;
                            }

                            $("#time" + code).html(t).show();


                            nowtimelimit += 1000;//当前时间每秒递增
                        };

                //本场抢购
                for (code in vm.codeToFlashsale) {
                    var
                            flashsale = vm.codeToFlashsale[code],
                            endtimelimit = flashsale.endtime * 1000;//结束时间，时间戳毫秒

                    if (!endtimelimitChange[code])
                        endtimelimitChange[code] = endtimelimit;

                    timego(code);
                    continue;
                }//end for

                //下一场抢购
                var loadGoodsInfo = false;
                for (code in vm.codeToFlashsaleNext) {
                    var flashsalenext = vm.codeToFlashsaleNext[code],
                            starttimelimit = flashsalenext.starttime * 1000;//开始时间，时间戳毫秒

                    if (new Date().getTime() >= starttimelimit) {
                        //清除过期的下一场数据
                        vm.codeToFlashsaleNext[code] = {};
                        vm.code2goods[code].nextFlashsaleStarttime = '';
                        $("#nexttime" + code).html('');
                        if (flashsalenextTimer)
                            clearTimeout(flashsalenextTimer);//下一场
                        loadGoodsInfo = true;
                    }
                }
                if (loadGoodsInfo) {
                    that.loadGoodsInfo();
                }

            }, 1000);

        },
        clearFullTimer: function() {
            if (flashsaleTimer)
                clearTimeout(flashsaleTimer);//进行场次
            if (flashsalenextTimer)
                clearTimeout(flashsalenextTimer);//下一场
            if (hqTimer)
                clearTimeout(hqTimer);//行情
            if (groupTimer)
                clearTimeout(groupTimer);
            if (goodsTimer)
                clearTimeout(goodsTimer);
        },
        onRouteChange: function() {
            if (vm) {
                vm.show = false;
                vm.tabIndex = '0';
            }
            this.clearFullTimer();
        }
    }
    return controller;
});